#!/bin/bash

if [ $# -ne 2 ]; then
	echo "Usage: $0 dot_file sub_function_node"
	exit 0
fi

IN_DOT_FILE=$1
IN_SUB_FUNC_NODE=$2
OUT_DOT_FILE="$1_no-$2.dot"
OUT_PNG_FILE="$1_no-$2.png"


FUNC_MAIN_ITEM=$(grep "\->${IN_SUB_FUNC_NODE};" "${IN_DOT_FILE}")

if [ -z "$FUNC_MAIN_ITEM" ]; then
	echo "ERROR: ${IN_SUB_FUNC_NODE} sub-function node not found"
	exit 1
#else
	#echo "FUNC_MAIN_ITEM: \"${FUNC_MAIN_ITEM}\"."
fi

MAIN_NODE=$(grep "\[shape=box\]" "${IN_DOT_FILE}" | sed "s/ \[shape=box\];//")
echo "[MAIN_NODE] ${MAIN_NODE}"

rm_sub_node() {
	local par1=$1
	local par2=$2

	echo "[CALL] rm_sub_node($par1, $par2)"

	local SUB_LIST=$(grep " $par2\->" "$par1")
	#echo "grep $par2 in $par1"
	#echo "SUB_LIST: $SUB_LIST."

	if [ -n "$SUB_LIST" ]; then
		#echo step 1: remove sub node
		SED_CMD="/ $par2->/d"
		sed "$SED_CMD" "$par1" > "$par1.tmp1"
		#echo "[NEW DOT] $par1.tmp1"
		END_DOT_FILE="$par1.tmp1"

		#echo step 2: loop remove isolated node
		SED_CMD="/ $par2->/w $par1.tmp2"
		sed "$SED_CMD" "$par1" >/dev/null
		SED_CMD="s/node.* $par2->\(.*\);/\1/"
		sed "$SED_CMD" "$par1.tmp2" > "$par1.tmp3"

		# loop call
		for index in $(cat "$par1.tmp3"); do
			SUB_SUB_LIST=$(grep "\->$index;" "$END_DOT_FILE")
			if [ -z "$SUB_SUB_LIST" -a "$index" != "$MAIN_NODE" ]; then
				rm_sub_node "$END_DOT_FILE" $index
			fi

			SUB_SUB_LIST=$(grep "$index \[label" "$END_DOT_FILE")
			if [ -n "$SUB_SUB_LIST" ]; then
				SED_CMD="/$index \[label/d"
				sed "$SED_CMD" "$END_DOT_FILE" > "$END_DOT_FILE.tmp"
				END_DOT_FILE="$END_DOT_FILE.tmp"
			fi
		done
	fi
}

# process dot file
END_DOT_FILE="${IN_DOT_FILE}"

. ./config

TMP_IN_FILE="$ITMP_PATH/$(basename $IN_DOT_FILE)"
cp -f $IN_DOT_FILE $TMP_IN_FILE
IN_DOT_FILE=$TMP_IN_FILE

rm_sub_node "${IN_DOT_FILE}" ${IN_SUB_FUNC_NODE}

# in the sub-function, append "..."
SED_CMD="s/}/$IN_SUB_FUNC_NODE \[label=\"$IN_SUB_FUNC_NODE ...\"\];\n}/"
sed "$SED_CMD" "$END_DOT_FILE" > "${IN_DOT_FILE}.tmp"
END_DOT_FILE="${IN_DOT_FILE}.tmp"
mv "$END_DOT_FILE" "$OUT_DOT_FILE"

echo "OUT_DOT_FILE: \"$OUT_DOT_FILE\""
echo "OUT_PNG_FILE: \"$OUT_PNG_FILE\""

#remove tmp file
rm -rf ${TMP_IN_FILE}*

dot -Tpng -o "${OUT_PNG_FILE}" "${OUT_DOT_FILE}"

if [ -n "$PIC_TOOLS" ]; then
	$PIC_TOOLS "$OUT_PNG_FILE" >/dev/null 2>&1
fi
